package com.geeguo.ebuilder.client.base.tenant.proxy.impl;

import com.geeguo.ebuilder.client.base.tenant.model.TenantInfo;
import com.geeguo.ebuilder.client.base.tenant.model.TenantInfoConverter;
import com.geeguo.ebuilder.client.base.tenant.model.TenantInfoRO;
import com.geeguo.ebuilder.client.base.tenant.proxy.TenantInfoProxy;
import com.geeguo.ebuilder.client.base.tenant.remote.TenantInfoApi;
import com.geeguo.ebuilder.core.common.action.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class TenantInfoProxyImpl implements TenantInfoProxy {

    private final Map<String, TenantInfo> tenantInfoMapps = new ConcurrentHashMap<String, TenantInfo>();
    
    @Autowired
    private TenantInfoApi tenantInfoApi;
    
    @Override
    public TenantInfo getByCode(String code) {
    	TenantInfo result = tenantInfoMapps.get(code);
        if (result == null) {
        	ActionResult<TenantInfoRO> actionResult = tenantInfoApi.getByCode(code);
            if (actionResult.isSuccess()) {
            	TenantInfoRO tenantInfo = actionResult.getData();
            	if (tenantInfo != null) {
            		result = TenantInfoConverter.INSTANCE.convert2Info(tenantInfo);
                    tenantInfoMapps.put(result.getCode(), result);
            	}
            }
        }
        return result;
    }

    @Override
    public TenantInfo getByDomain(String domain) {
    	TenantInfo result = null;
        for (TenantInfo tenantInfo : tenantInfoMapps.values()) {
            if (tenantInfo.getDomain().equals(domain)) {
                result = tenantInfo;
                break;
            }
        }
        if (result == null) {
        	ActionResult<TenantInfoRO> actionResult = tenantInfoApi.getByDomain(domain);
            if (actionResult.isSuccess()) {
            	TenantInfoRO tenantInfo = actionResult.getData();
            	if (tenantInfo != null) {
            		result = TenantInfoConverter.INSTANCE.convert2Info(tenantInfo);
                    tenantInfoMapps.put(result.getCode(), result);
            	}
            }
        }
        return result;
    }
    
    @Override
    public boolean isValid(String code) {
        return tenantInfoMapps.containsKey(code);
    }
    
    @Override
    public void refreshByCode(String code) {
    	ActionResult<TenantInfoRO> actionResult = tenantInfoApi.getByCode(code);
        if (actionResult.isSuccess()) {
        	TenantInfoRO tenantInfo = actionResult.getData();
        	if (tenantInfo != null) {
        		TenantInfo info = TenantInfoConverter.INSTANCE.convert2Info(tenantInfo);
                tenantInfoMapps.put(info.getCode(), info);
        	}
        }
    }
    
	@Override
	public void clearByCode(String code) {
        tenantInfoMapps.remove(code);
	}
}